﻿<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head th:include="./common/head :: head"></head>
<body style="background-color: #ecf0f1;">
<style type="text/css">
    .mylevel-row {
        background-color: #95a5a6;
    }

    .mylevel-row1 {
        background-color: #ecf0f1;
    }

    .dropdown-menu {
        min-width: 100px;
    }

    .dropdown-menu li {
        width: 100px;
    }
</style>

<script type="text/javascript" th:inline="javascript">
    var contextPath = [[${session.ctx}]];
    var username = [[${session.user.name}]];
    var userId = [[${session.user.id}]];
    $(function () {
        common.render("#cover,#editCover", userId);
        $('#catagroy').bootstrapTable({
            method: 'GET',
            dataType: 'json',
            contentType: "application/x-www-form-urlencoded",
            cache: false,
            striped: true,                              //是否显示行间隔色
            sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
            url: contextPath + '/category',
            height: $(window).height() - 110,
            width: $(window).width(),
            showColumns: true,
            pagination: true,
            queryParamsType: "other",
            toolbar: "#toolbar",
            toolbarAlign: "left",
            queryParams: function (params) {
                var param = {
                    pn: params.pageNumber,
                    ps: params.pageSize,
                    // pageSize: params.pageSize,
                    // pageNumber: params.pageNumber,
                    name: params.searchText,
                    // sortName: "",
                    // sortOrder: "",
                    cover: $('#cover').val(),
                    parentName: username
                }
                return param;
            },
            minimumCountColumns: 2,
            pageNumber: 1,        //初始化加载第一页，默认第一页
            pageSize: 10,            //每页的记录行数（*）
            pageList: [10, 25, 50, 100],       //可供选择的每页的行数（*）
            uniqueId: "id",      //每一行的唯一标识，一般为主键列
            showExport: true,
            exportDataType: 'all',
            search: true,
            searchTimeOut: 1500,
            searchOnEnterKey: true,
            responseHandler: function (data) {
                var data1 = {
                    total: data.totalCount,
                    rows: data.items
                }
                return data1;
            },
            onLoadSuccess: function (data) {
            },
            columns: [{
                field: 'id',
                title: 'ID',
                width: '5%',
                visible: false,
                formatter: function (value, row, index) {
                    return row.id;
                }
            }, {
                field: 'name',
                title: '链接名称',
                align: 'center',
                valign: 'middle',
                width: '15%',
            }, {
                field: 'cover',
                title: '分类',
                align: 'center',
                valign: 'middle',
                width: '5%',
                formatter: function (value, row, index) {
                    var str = "";
                    $(common.categoryCoverList).each(function (i) {
                        if (this.id == row.cover) {
                            str = this.coverName;
                            return false;
                        }
                    })
                    return str;
                }
            }, {
                field: 'ancestors',
                title: '地址',
                align: 'left',
                valign: 'middle',
                width: '450px',
                formatter: function (value, row, index) {
                    var length = value != null ? value.length : 0;
                    var show = value;
                    if (length > 50) {
                        show = value.substring(0, 50) + "...";
                    }
                    return "<a target='_blank' href='" + value + "'>" + show + "</a>";
                }
            }, {
                field: 'level',
                title: '公开/私有',
                align: 'center',
                valign: 'middle',
                width: '100px',
                formatter: function (value, row, index) {
                    var str = row.level ? "<span class=\"label label-info\">公开</span>" :
                        "<span class=\"label label-warning\">私有</span>";
                    return str;
                }
            }, {
                field: 'description',
                title: '描述',
                align: 'left',
                valign: 'middle',
                width: '150px',
                formatter: function (value, row, index) {
                    var length = value != null ? value.length : 0;
                    var show = value;
                    if (length > 50) {
                        show = value.substring(0, 50) + "...";
                    }
                    return show;
                }
            }, {
                field: '',
                title: '操作',
                align: 'center',
                valign: 'middle',
                width: '10%',
                formatter: function (value, row, index) {
                    var ht = $("<div></div>").append($('#operDrop')[0].outerHTML);
                    ht.attr('data-id', row.id).attr("id", "");
                    ht.find("button[id='dropdownMenu']").attr("id", "dropdownMenu" + row.id);
                    ht.find(".dropdown-menu").attr("aria-labelledby", "dropdownMenu" + row.id);
                    ht.find('.my-del').attr('onclick', "del(" + row.id + ")");
                    ht.find('.my-edit').attr('onclick', "edit(" + row.id + ")");
                    if (row.level) {
                        ht.find('.my-share').attr('onclick', "share(" + row.id + "," + row.level + ")").find(".share-text").text("取消分享");
                    } else {
                        ht.find('.my-share').attr('onclick', "share(" + row.id + "," + row.level + ")").find(".share-text").text("分享");
                    }
                    return ht.html();
                }
            }]
        });

        $("#confirmDelBtn").click(function (e) {
            var id = $('#confirmModal').data("id");
            http.del("category", id, function (data) {
                if (data.success) {
                    toastr.success('删除成功');
                    $('#confirmModal').modal('hide');
                    search();
                } else {
                    toastr.warning('删除失败');
                    $('#confirmModal').modal('hide');
                }
            })
        });


        $("#editForm").bootstrapValidator({
            live: 'disabled',//验证时机，enabled是内容有变化就验证（默认），disabled和submitted是提交再验证
            excluded: [':disabled', ':hidden', ':not(:visible)'],//排除无需验证的控件，比如被禁用的或者被隐藏的
            submitButtons: '#confirmSaveBtn',//指定提交按钮，如果验证失败则变成disabled，但我没试成功，反而加了这句话非submit按钮也会提交到action指定页面
            message: '验证失败',//好像从来没出现过
            feedbackIcons: {//根据验证结果显示的各种图标
                valid: 'glyphicon glyphicon-ok',
                invalid: 'glyphicon glyphicon-remove',
                validating: 'glyphicon glyphicon-refresh'
            },
            fields: {
                name: {
                    validators: {
                        notEmpty: {//检测非空,radio也可用
                            message: '名称必须输入'
                        },
                    }
                },
                cover: {
                    validators: {
                        notEmpty: {//检测非空,radio也可用
                            message: '请选择分类'
                        },
                    }
                },
                ancestors: {
                    validators: {
                        notEmpty: {//检测非空,radio也可用
                            message: '收藏地址必须输入'
                        },
                        regexp: {
                            regexp: /^(http|https):\/\/.*/,
                            message: '收藏地址不正确'
                        }
                    }
                },
            }
        }).on('success.form.bv', function (e) {//点击提交之后
            e.preventDefault();
            var data = $(e.target).serializeJSON();
            if (common.isNull(data.id)) {
                data.parentName = username;
                data.level = false;
                http.add("category", data, function (data) {
                    if (data.success) {
                        toastr.success('保存成功');
                        $('#editModal').modal('hide');
                        search();
                    } else {
                        toastr.warning('保存失败');
                        $('#editModal').modal('hide');
                    }
                });
            } else {
                http.update("category", data, function (data) {
                    if (data.success) {
                        toastr.success('保存成功');
                        $('#editModal').modal('hide');
                        search();
                    } else {
                        toastr.warning('保存失败');
                        $('#editModal').modal('hide');
                    }
                });
            }
        });

        common.coverPoper();

    });

    function coverSave() {
        var data = $("#coverSaveForm").serializeJSON();
        data.userId = userId;
        http.add("categoryCover", data, function (resp) {
            if (resp.success) {
                toastr.success('保存成功,已设置该收藏为分类：' + resp.data.coverName);
                $("#coverAddBtn").popover("hide");
                $("#editCover").append("<option value='" + resp.data.id + "'>" + resp.data.coverName + "</option>")
                    .val(+resp.data.id);
            } else {
                toastr.warning('保存失败');
                $("#coverAddBtn").popover("hide");
            }
        }, function (resp) {
            if (resp.responseText.indexOf("Duplicate entry")) {
                toastr.error('保存失败，分类名称重复');
            } else {
                toastr.error('保存失败');
            }
            $("#coverAddBtn").popover("hide");
        });
    }

    function del(id) {
        $('#confirmModal').data("id", id).modal('show');
    }

    function edit(id) {
        if (common.isNull(id)) {
            common.clearForm("#editForm");
            // $("#editAncestors").removeAttr("disabled");
            $("#editUpdated").closest(".form-group").hide();
            $('#editModal').modal('show');

        } else {
            var row = $('#catagroy').bootstrapTable('getRowByUniqueId', id);
            $("#editForm").loadJson(row);
            // $("#editAncestors").attr("disabled","disabled");
            $("#editUpdated").closest(".form-group").show();
            $('#editModal').data("id", id).modal('show');
        }

    }

    function share(id, level) {
        var str = level ? "取消分享" : "分享";
        http.update("category", {
            id: id,
            level: !level
        }, function (data) {
            if (data.success) {
                toastr.success(str + '成功！');
                search();
            } else {
                toastr.warning(str + '失败！');
            }
        })
    }

    function search() {
        $('#catagroy').bootstrapTable('refresh');
    }


</script>
<div class="container-fluid">
    <header th:include="./common/header :: header"></header>
    <div class="row">
        <div th:include="./common/leftMenu :: leftMenu" class="col-md-3"></div>
        <div class="col-md-9">
            <table id="catagroy"></table>
        </div>
        <div id="toolbar">
            <form class="form-inline">
                <div class="form-group" style="padding-right: 50px;">
                    <button id="create" type="button" onclick="edit()" class="btn btn-success"><span
                            class="glyphicon glyphicon-plus" aria-hidden="true">&nbsp;创建收藏</span></button>
                </div>
                <div class="form-group">
                    <label for="cover">分类：</label>
                    <select id="cover" class="form-control" onchange="search()" style="width: 150px;"></select>
                </div>
            </form>
        </div>

    </div>
    <div class="hide">
        <div id="operDrop" class="dropdown">
            <button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu" data-toggle="dropdown"
                    aria-haspopup="true" aria-expanded="true">
                <span class="glyphicon glyphicon-cog"></span>&nbsp;
                <span class="caret"></span>
            </button>
            <ul class="dropdown-menu" aria-labelledby="dropdownMenu" data-id="">
                <li><a class="my-edit" href="#"><span class="glyphicon glyphicon-edit"></span>&nbsp;修改</a></li>
                <li><a class="my-del" href="#"><span class="glyphicon glyphicon-trash"></span>&nbsp;删除</a></li>
                <li role="separator" class="divider"></li>
                <li><a class="my-share" href="#"><span class="glyphicon glyphicon-share"></span>&nbsp;<span
                        class="share-text">取消分享</span></a></li>
            </ul>
        </div>
    </div>

    <!-- confirm Modal -->
    <div class="modal fade bs-example-modal-sm" id="confirmModal" tabindex="-1" role="dialog"
         aria-labelledby="confirmModalLabel">
        <div class="modal-dialog bs-example-modal-sm" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                            aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title" id="confirmModalLabel">确认删除?</h4>
                </div>
                <div class="modal-body">
                    您确认删除该记录吗？
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                    <button id="confirmDelBtn" type="button" class="btn btn-success">确认</button>
                </div>
            </div>
        </div>
    </div>

    <!-- edit Modal -->
    <div class="modal fade bs-example-modal-sm" id="editModal" tabindex="-1" role="dialog"
         aria-labelledby="editModalLabel">
        <div class="modal-dialog bs-example-modal-sm" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                            aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title" id="editModalLabel">收藏链接</h4>
                </div>
                <form id="editForm">
                    <div class="modal-body">
                        <input type="hidden" name="id">
                        <div class="form-group">
                            <label for="editName">名称</label>
                            <input type="text" class="form-control" id="editName" name="name" placeholder="链接名称">
                        </div>
                        <!--<div class="input-group-addon"><button type="button"  class="btn btn-success"><span-->
                        <!--class="glyphicon glyphicon-plus" aria-hidden="true"></span>-->
                        <!--</button>  </div>-->
                        <div class="form-group">
                            <div class="row" style="padding: 0 15px">
                                <label for="editCover">分类</label>
                            </div>
                            <div class="row" style="padding: 0 15px">
                                <div style="float:left;width: 90%;">
                                    <select class="form-control" id="editCover" name="cover"></select>
                                </div>
                                <div style="float:left;width: 10%;">
                                    <button id="coverAddBtn" type="button" class="btn btn-success"><span
                                            class="glyphicon glyphicon-plus" aria-hidden="true"></span>
                                    </button>
                                </div>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="editAncestors">地址</label>
                            <textarea type="text" class="form-control" id="editAncestors" name="ancestors" rows="3"
                                      placeholder="http(s)://"></textarea>
                        </div>
                        <div class="form-group">
                            <label for="editDescription">描述</label>
                            <input type="text" class="form-control" id="editDescription" name="description"
                                   placeholder="描述">
                        </div>
                        <div class="form-group">
                            <label for="editUpdated">更新时间</label>
                            <input type="text" class="form-control" id="editUpdated" name="updated" placeholder="更新时间"
                                   disabled="disabled">
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                        <button id="confirmSaveBtn" type="submit" class="btn btn-success">确认</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    <!--分类-->
    <div id="coverAddTip" class="hide">
        <form id="coverSaveForm" class="form-horizontal" style="width:180px;">
            <div class="form-group">
                <div class="col-xs-12 col-md-12">
                    <input type="text" class="form-control popover-field" name="coverName" placeholder="分类名称">
                </div>
            </div>
            <div class="form-group">
                <div class="col-md-12 col-sm-12">
                    <button id="coverSaveBtn" onclick="coverSave()" type="button"
                            class="btn btn-success btn-block coverSaveBtn popover-field">添加
                    </button>
                </div>
            </div>
        </form>
    </div>

</div>
</body>
</html>